package com.letv.core.download.image;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.text.TextUtils;

/**
 * 图片下载器
 * 
 * @author zhuqiao
 *
 */
public class DownloaderFromHttp {

    /**
     * 请求网络的inputStream填充outputStream
     * 
     * @param url
     * 图片地址
     * @return
     */
    public static boolean download(String urlString, OutputStream outputStream) {
        if (TextUtils.isEmpty(urlString) || !urlString.startsWith("http"))
            return false;

        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            out = new BufferedOutputStream(outputStream, 8 * 1024);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 请求网络的inputStream填充outputStream
     * 
     * @param url
     * 图片地址
     * @return
     */
    public static byte[] download(String urlString) {
        if (TextUtils.isEmpty(urlString) || !urlString.startsWith("http"))
            return null;

        HttpURLConnection conn = null;
        InputStream in = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            in = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int readed;
            while ((readed = in.read()) != -1) {
                baos.write(readed);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.disconnect();
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }

}
